package com.lxc.crud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lxc.crud.entity.User;
import com.lxc.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserService userService;
    //功能：post，添加数据
    @ResponseBody
    @PostMapping("/user")//测试示例：{"name":"奥特曼1","age":18,"email":"123@aoteman.com","address":"泰坦星球"}
    public String saveUser(@RequestBody String user1){
       User user =  JSONObject.parseObject(user1,User.class);
        userService.saveUser(user);
        System.out.println(user);
        return "保存一条记录到数据库:user1";
    }
    //批量查询功能
    @GetMapping("/user/{ids}")//测试参数示例：/user/1,2,3,4
    @ResponseBody
    public String getUsers(@PathVariable String ids){
        List<String> allNum = Arrays.asList(ids.split(","));
        List<Integer> numList = new ArrayList<Integer>();
        List<User> userList = userService.findUsers(ids);
       String userString = JSON.toJSONString(userList);
        return "查询数据库结果："+userString;
    }

    //多条件查询，缺省参数以空格代替
    @GetMapping("/user/{id}/{name}/{age}/{email}/{address}")
    @ResponseBody
    public String getUser(@PathVariable String id,@PathVariable String name,@PathVariable String age,@PathVariable String email,@PathVariable String address){

        User user = new User();
        if(!id.equals(" "))
        user.setId(Integer.parseInt(id));
        if(!name.equals(" "))
        user.setName(name);
        if(!age.equals(" "))
        user.setAge(Integer.parseInt(age));
        if(!email.equals(" "))
        user.setEmail(email);
        if(!email.equals(" "))
        user.setAddress(address);
        List<User> userList = userService.findUser(user);

        String userString = JSON.toJSONString(userList);
        return "多条件查询:"+userString;
    }

    //修改数据，以json字符串，在请求体内传输,根据id匹配，示例：{"name":"奥特曼1","age":18,"email":"123@aoteman.com","address":"泰坦星球","id":2}，
    //缺省值，直接不写对应的参数
    @PutMapping("/user")
    @ResponseBody
    public String updateUser(@RequestBody String userString){
        User user = JSON.parseObject(userString,User.class);
        int num = userService.updateUser(user);
        return "修改数据："+String.valueOf(num);
    }

    //删除数据
    @DeleteMapping("/user/{id}")
    @ResponseBody
    public String deleteUser(@PathVariable String id){
        int num = userService.deleteUser(Integer.parseInt(id));
        return "删除数据："+String.valueOf(num);
    }
}
